#ifndef UNIQUEIDGENERATOR_H
#define UNIQUEIDGENERATOR_H

#include <iostream>
#include <string>
#include <chrono>
#include <sstream>
#include <iomanip>
#include <mutex>

class UniqueIDGenerator {
private:
    int dailySequenceNumber;
    std::string lastDate;
    std::mutex mtx; // 用于线程安全的锁
    UniqueIDGenerator() : dailySequenceNumber(0), lastDate("") {}
    ~UniqueIDGenerator() {}

public:
    // 删除拷贝构造函数和赋值操作符，确保单例
    UniqueIDGenerator(const UniqueIDGenerator&) = delete;
    UniqueIDGenerator& operator=(const UniqueIDGenerator&) = delete;

    static UniqueIDGenerator& getInstance() {
        static UniqueIDGenerator instance;
        return instance;
    }

    std::string getCurrentDate() {
        // 获取当前日期
        auto now = std::chrono::system_clock::now();
        auto now_c = std::chrono::system_clock::to_time_t(now);
        auto now_tm = *std::localtime(&now_c);

        std::ostringstream dateStream;
        dateStream << std::put_time(&now_tm, "%Y%m%d"); // 格式化日期为年月日
        return dateStream.str();
    }

    std::string generateID() {
        std::lock_guard<std::mutex> guard(mtx); // 确保线程安全

        std::string currentDate = getCurrentDate();

        if (currentDate != lastDate) {
            // 如果日期变了，重置序号并更新最后日期
            dailySequenceNumber = 1;
            lastDate = currentDate;
        } else {
            // 否则，序号自增
            ++dailySequenceNumber;
        }

        std::ostringstream idStream;
        idStream << currentDate << "-" << std::setw(5) << std::setfill('0') << dailySequenceNumber; // 生成ID

        return idStream.str();
    }

    std::size_t getDailySequenceNumber() {
        std::lock_guard<std::mutex> guard(mtx); // 确保线程安全
        return dailySequenceNumber;
    }
};

#endif // UNIQUEIDGENERATOR_H